//
//  MTLiveApiManager.m
//  MeToo
//
//  Created by 俊松何 on 2018/7/19.
//  Copyright © 2018年 tianxie. All rights reserved.
//

#import "MTLiveApiManager.h"
#import "YTKKeyValueStore.h"
#import "ZipArchive.h"
static MTLiveApiManager *liveApimanager = nil;
@interface MTLiveApiManager()
@property(nonatomic,strong) YTKKeyValueStore *store;
@end


@implementation MTLiveApiManager

+(instancetype)manager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        liveApimanager = [[MTLiveApiManager alloc] init];
    });
    return liveApimanager;
}
-(YTKKeyValueStore *)store
{
    if(_store == nil)
    {
        _store = [[YTKKeyValueStore alloc] initDBWithName:MiTuCacheDBName];
        [_store createTableWithName:LiveTableName];
    }
    return _store;
}

/**
 关闭直播间
 
 @param liveId 直播liveId
 @param completionBlock 完成block
 */
-(void)closeLive:(NSString *)liveId
      completion:(void (^)(MTError *error))completionBlock
{
    NSDictionary *param = @{@"liveId":liveId};
    [[MTHttpTool shareTool] postPath:@"/live/close" parameters:param success:^(MTBaseData *datamodel) {
        completionBlock(nil);
    } failer:completionBlock];
}

/**
 加入直播间
 
 @param liveId 房间id
 @param completionBlock 完成block
 */
-(void)joinLive:(NSString *)liveId
     completion:(void (^)(MTError *error))completionBlock
{
    NSDictionary *param = @{@"liveId":liveId};
    [[MTHttpTool shareTool] postPath:@"/live/join" parameters:param success:^(MTBaseData *datamodel) {
        completionBlock(nil);
    } failer:completionBlock];
}

/**
 创建直播
 
 @param title 直播title
 @param cover cover
 @param topics 话题
 @param completionBlock 完成block
 */
-(void)createLiveWithTitle:(NSString *)title
                     cover:(NSString *)cover
                    topics:(NSString *)topics
                    typeId:(NSInteger)typeId
                completion:(void (^)(MTLiveModel* liveModel,MTError *error))completionBlock
{
    if(title.length == 0)
    {
        title = [LTClient sharedClient].currentUser.name;
    }
    NSDictionary *param = @{@"cover":cover,@"topics":topics,@"title":title,@"typeId":@(typeId)};
    [[MTHttpTool shareTool] postPath:@"/live/open" parameters:param success:^(MTBaseData *datamodel) {
        MTLiveModel *model = [MTLiveModel mj_objectWithKeyValues:datamodel.data];
        completionBlock(model,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}

/**
 退出直播
 
 @param liveId 直播id
 @param completionBlock 完成block
 */
-(void)quiteLive:(NSString *)liveId
      completion:(void (^)(MTError *error))completionBlock
{
    NSDictionary *param = @{@"liveId":liveId};
    [[MTHttpTool shareTool] postPath:@"/live/quite" parameters:param success:^(MTBaseData *datamodel) {
        completionBlock(nil);
    } failer:completionBlock];
}

/**
 保存直播回放
 
 @param liveId 直播id
 @param completionBlock 完成block
 */
-(void)saveLivePlayback:(NSString *)liveId
             completion:(void (^)(MTError *error))completionBlock
{
    NSDictionary *param = @{@"liveId":liveId};
    [[MTHttpTool shareTool] postPath:@"/live/save_live" parameters:param success:^(MTBaseData *datamodel) {
        completionBlock(nil);
    } failer:completionBlock];
    
}

/**
 获取直播间的观众列表
 
 @param liveId 直播Id
 @param completionBlock 完成block
 */
-(void)getLiveViewersWithLiveId:(NSString *)liveId
                     completion:(void (^)(NSMutableArray<LTUser *> *viewers, MTError *error))completionBlock
{
    NSDictionary* requestDic = @{@"page":@"1",@"liveId":liveId};
    [[MTHttpTool shareTool] getPath:@"/live/viewers" parameters:requestDic success:^(MTBaseData *datamodel) {
        NSMutableArray<LTUser *>* users = [LTUser mj_objectArrayWithKeyValuesArray:datamodel.data[@"list"]];
        completionBlock(users,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}

/**
 获取热门直播列表
 
 @param page page
 @param completionBlock 完成block
 */
-(void)gethotLiveListWithpage:(int)page
                   completion:(void (^)(MTLiveTotalModel *livetotalModel, MTError *error))completionBlock
{
    NSDictionary* requestDic = @{@"page":@(page)};
    [[MTHttpTool shareTool] getPath:@"/live/hot" parameters:requestDic success:^(MTBaseData *datamodel) {
        MTLiveTotalModel* model = [MTLiveTotalModel mj_objectWithKeyValues:datamodel.data];
        completionBlock(model,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}

/**
 获取直播间礼物列表
 
 @param completionBlock 完成block
 */
-(void)getGiftsWithComplation:(void (^)(NSMutableArray<giftModel *> *gifts, MTError *error))completionBlock
{
    [[MTHttpTool shareTool] getPath:@"/live/gifts" parameters:nil success:^(MTBaseData *datamodel){
        [self.store putObject:datamodel.data withId:giftskey intoTable:LiveTableName];
        NSMutableArray* tempArray = [giftModel mj_objectArrayWithKeyValuesArray:datamodel.data];
        completionBlock(tempArray,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}

-(void)downloadGift
{
    
    [[MTHttpTool shareTool] getPath:@"/live/gifts" parameters:nil success:^(MTBaseData *datamodel){
        NSMutableArray<giftModel *> *tempArray = [giftModel mj_objectArrayWithKeyValuesArray:datamodel.data];
        NSMutableArray *bigGiftArray = [[NSMutableArray alloc] initWithCapacity:3];
        for (giftModel *model in tempArray) {
            if(model.animation)
            {
                [bigGiftArray addObject:model];
            }
        }
        for (giftModel * model in bigGiftArray) {
            
            NSString *filepath = [NSString stringWithFormat:@"%@/%@%@",cachePath, model.englishTitle,model.version];
            NSData * data = [NSData dataWithContentsOfFile:filepath];
            
            //如果缓存路径不存在，或者数据大小为0 就下载
            if (![[NSFileManager defaultManager] fileExistsAtPath:filepath]  || data.length == 0) {
                
                NSURL *url = [NSURL URLWithString:model.animationUrl];
                NSURLRequest *request = [NSURLRequest requestWithURL:url];
                NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
                AFURLSessionManager *manger = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
                NSURLSessionDownloadTask *downloadTask = [manger downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
                    
                } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                    
                    NSURL *downurl = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
                    NSString * address = [NSString stringWithFormat:@"%@%@.zip", model.englishTitle, model.version];
                    
                    return [downurl URLByAppendingPathComponent:address];
                } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                    
                    NSString *filepath = [NSString stringWithFormat:@"%@/%@%@.zip",cachePath, model.englishTitle, model.version];
                    NSString * newFilePath = [NSString stringWithFormat:@"%@/%@",cachePath,model.englishTitle];
                    ZipArchive * archive = [[ZipArchive alloc]init];
                    [archive UnzipOpenFile:filepath];
                    [archive UnzipFileTo:newFilePath overWrite:YES];
                }];
                [downloadTask resume];
            }
        }
    } failer:^(MTError *error) {
       
    }];
    
    
    
    
}






/**
 送礼物
 
 @param anchorId 主播id
 @param giftId 礼物id
 @param liveId 直播间id
 @param password 用户钱包密码
 @param token  后面token指令
 @param completionBlock 完成block
 */
-(void)sendGiftWithAnchorId:(NSString *)anchorId
                     giftId:(NSString *)giftId
                     liveId:(NSString *)liveId
                   password:(NSString *)password
                      token:(NSString *)token
                 completion:(void (^)(NSString *token, MTError *error))completionBlock
{
    NSDictionary *param = @{@"anchorId":anchorId,@"giftId":giftId,@"liveId":liveId};
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:param];
    if(password != nil)
    {
         NSString *crypPassword =    [LTAESTool decryptAES:password key:passwordCrypkey kVector:passwordCrypInvterKey];
         [dict setObject:crypPassword forKey:@"password"];
    }else if(token != nil)
    {
        NSString *cryptoken =    [LTAESTool decryptAES:token key:passwordCrypkey kVector:passwordCrypInvterKey];
        [dict setObject:cryptoken forKey:@"token"];
    }
    [[MTHttpTool shareTool] postPath:@"/live/send_gift" parameters:dict success:^(MTBaseData *datamodel) {
        completionBlock(datamodel.data,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}


/**
 通过直播ID获取直播详情
 
 @param liveId 直播id
 @param completionBlock 完成block
 */
-(void)getLiveInfoWithLiveId:(NSString *)liveId
                  completion:(void (^)(MTLiveModel *liveModel, MTError *error))completionBlock
{
    NSDictionary *param = @{@"liveId":liveId};
    [[MTHttpTool shareTool] getPath:@"/live/info" parameters:param success:^(MTBaseData *datamodel) {
        MTLiveModel *model = [MTLiveModel mj_objectWithKeyValues:datamodel.data];
        completionBlock(model,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}

/**
 发送弹幕
 
 @param completionBlock 完成block
 */
-(void)sendBarrageWithcompletion:(void (^)(MTError *error))completionBlock
{
    [[MTHttpTool shareTool] postPath:@"/live/send_barrage" parameters:nil    success:^(MTBaseData *datamodel) {
        completionBlock(nil);
    } failer:completionBlock];
}


/**
 获取回放列表
 
 @param page 页数
 @param userId userid
 @param completionBlock block
 */
-(void)getReplayListWithpage:(int)page
                      userId:(NSString *)userId
                  completion:(void (^)(MTLiveTotalModel *livetotalModel, MTError *error))completionBlock
{
    NSDictionary* requestDic = @{@"page":@(page),
                                 @"userId":userId
                                 };
    [[MTHttpTool shareTool] getPath:@"/live/get_user_replay" parameters:requestDic success:^(MTBaseData *datamodel) {
        MTLiveTotalModel* model = [MTLiveTotalModel mj_objectWithKeyValues:datamodel.data];
        completionBlock(model,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
    
}

/**
 删除回放
 
 @param liveId 直播id
 @param completionBlock block
 */
-(void)deleteReplayWithLiveId:(NSString *)liveId
                   completion:(void (^)(MTError *error))completionBlock
{
    NSDictionary* requestDic = @{@"liveId":liveId,
                                 };
    [[MTHttpTool shareTool] postPath:@"/live/delete_live" parameters:requestDic success:^(MTBaseData *datamodel) {
        completionBlock(nil);
    } failer:^(MTError *error) {
        completionBlock(error);
    }];
    
}

-(void)getliveTypesWithcompletion:(void (^)(NSMutableArray<MTLiveTypeModel *> *types,MTError *error))completionBlock
{
    [[MTHttpTool shareTool] getPath:@"/live/get_types" parameters:nil success:^(MTBaseData *datamodel) {
        NSMutableArray *dataArray = [MTLiveTypeModel mj_objectArrayWithKeyValuesArray:datamodel.data];
        completionBlock(dataArray,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}


/**
 获取showtypes
 
 @param completionBlock block
 */
-(void)getshowliveTypesWithcompletion:(void (^)(NSMutableArray<MTLiveTypeModel *> *types,MTError *error))completionBlock
{
    [[MTHttpTool shareTool] getPath:@"/live/get_show_types" parameters:nil success:^(MTBaseData *datamodel) {
        NSMutableArray *dataArray = [MTLiveTypeModel mj_objectArrayWithKeyValuesArray:datamodel.data];
        completionBlock(dataArray,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
    
}


/**
 获取热门直播列表
 
 @param page page
 @param completionBlock 完成block
 */
-(void)gettypeLiveListWithpage:(int)page
                        typeId:(NSInteger)typeId
                   completion:(void (^)(MTLiveTotalModel *livetotalModel, MTError *error))completionBlock
{
    NSDictionary* requestDic = @{@"page":@(page),
                                 @"typeId":@(typeId)};
    [[MTHttpTool shareTool] getPath:@"/live/get_by_types" parameters:requestDic success:^(MTBaseData *datamodel) {
        MTLiveTotalModel* model = [MTLiveTotalModel mj_objectWithKeyValues:datamodel.data];
        completionBlock(model,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}


/**
 管理员或者主播禁言用户

 @param masterUserId 直播Id
 @param targetUserId targetUserId
 @param completionBlock 完成block
 */
-(void)muteUsermasterUserId:(NSString *)masterUserId
               targetUserId:(NSString *)targetUserId
                 completion:(void (^)(MTError *error))completionBlock
{
    NSDictionary* requestDic = @{@"masterUserId":masterUserId,
                                 @"targetUserId":targetUserId};
    [[MTHttpTool shareTool] postPath:@"/live/force_no_speaking" parameters:requestDic success:^(MTBaseData *datamodel) {
        completionBlock(nil);
    } failer:^(MTError *error) {
        completionBlock(error);
    }];
}

/**
 主播踢出用户
 
 @param liveId 直播Id
 @param targetUserId targetUserId
 @param completionBlock 完成block
 */
-(void)kickOutUserLiveId:(NSString *)liveId
            targetUserId:(NSString *)targetUserId
              completion:(void (^)(MTError *error))completionBlock
{
    NSDictionary* requestDic = @{@"liveId":liveId,
                                 @"targetUserId":targetUserId};
    [[MTHttpTool shareTool] postPath:@"/live/force_quite" parameters:requestDic success:^(MTBaseData *datamodel) {
        completionBlock(nil);
    } failer:^(MTError *error) {
        completionBlock(error);
    }];
}



/**
 修改直播title

 @param liveId 直播Id
 @param title title
 @param completionBlock 完成block
 */
-(void)modifyLiveTitleLiveId:(NSString *)liveId
                       title:(NSString *)title
                  completion:(void (^)(MTError *error))completionBlock
{
    
    NSDictionary* requestDic = @{@"liveId":liveId,
                                 @"title":title};
    [[MTHttpTool shareTool] postPath:@"/live/modify_live_title" parameters:requestDic success:^(MTBaseData *datamodel) {
        completionBlock(nil);
    } failer:^(MTError *error) {
        completionBlock(error);
    }];
}


/**
 获取直播结束时候的信息

 @param liveId 直播ID
 @param completionBlock 完成block
 */
-(void)liveEndInfo:(NSString *)liveId
        completion:(void (^)(MTLiveModel *mdoel,MTError *error))completionBlock
{
    NSDictionary *param = @{@"liveId":liveId};
    [[MTHttpTool shareTool] postPath:@"/live/statistics" parameters:param success:^(MTBaseData *datamodel) {
        MTLiveModel *temp = [MTLiveModel mj_objectWithKeyValues:datamodel.data];
        completionBlock(temp,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}

@end
